public class leetcode557_反转字符串中的单词III {
    public static void main(String[] args) {
        Solution4 solution4 = new Solution4();
        System.out.println(solution4.reverseWords("Let's take LeetCode contest"));
        System.out.println("hello".substring(0, 4));
    }
}

class Solution4 {
    public String reverseWords(String s) {
        int fast = 0, slow = 0;
        StringBuilder result = new StringBuilder();
        while (fast < s.length()) {
            // 快指针遇到空格时，让满指针指向快指针指向的位置
            if (s.charAt(fast) == ' ') {
                result.append(reverseWord(s.substring(slow, fast).trim())).append(" ");
                slow = fast;
            }
            // 快指针达到字符串末尾时，需要substring需要fast+1，否则匹配不到最后一个字符
            if (fast == s.length() - 1) {
                result.append(reverseWord(s.substring(slow, fast + 1).trim()));
            }
            fast++;
        }
        return result.toString().trim();
    }

    private String reverseWord(String s){
        return new StringBuffer(s).reverse().toString();
    }
}
